package com.itheima.cookie;

import com.itheima.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/servletDemo3")
public class ServletDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取名称为lastTimeCookie对象
        Cookie[] cookies = request.getCookies();

        // 遍历数组，查找lastTimeCookie对象
//        Cookie cookie = null;
//        if (cookies != null) {
//            for (Cookie c : cookies) {
//                if ("lastTimeCookie".equals(c.getName())) {
//                    cookie = c;
//                    break;
//                }
//            }
//        }
        Cookie cookie = CookieUtils.findCookieByName(cookies, "lastTimeCookie");

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        // 判断cookie是否为null
        if (cookie == null) {
            // 首次访问
            writer.write("欢迎光临！！");
        } else {
            // 不是首次访问，获取Cookie中的值
            String time = cookie.getValue();
            writer.write("欢迎再次光临！！！您上次访问的时间是：" + time);
        }

        // 无论是否是第一次访问，使用Cookie记录当次的访问时间
        Cookie ck = new Cookie("lastTimeCookie",new Date().toLocaleString().replaceAll(" ",""));
        response.addCookie(ck);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
